import numpy
from PIL import Image
import numpy as np

img = Image.open('./image/lv.jpg').convert('L')
img = img.resize((int(img.width/10), int(img.height/10)))
print('size:', img.size, '\n')
# img.show()

a = np.array(img, dtype='float32')
a = np.trunc(a * 5 / 256) * 0.5
pos_begin = (0, 0)
pos_end = (0, 0)
cnt = 0
shift_flag = False

with open('./Soldmask.json', 'w') as f:
    with open('./part1.txt', 'r') as p:
        f.write(p.read())
    for i in range(img.height):
        shift_flag = True
        for j in range(img.width):
            x = 4070 + j * 2
            y = 3576.5 + i * 2
            d = a[i, j]
            if j + 1 >= img.width:
                d_next = 0
            else:
                d_next = a[i, j + 1]

            if shift_flag and d != 0:
                pos_begin = (x, y)
                shift_flag = False

            if d_next != d:
                pos_end = (x, y)
                if d != 0:
                    if pos_begin != pos_end:
                        f.write(
                            '    \"TRACK~' + str(d) + '~7~S$8~' + str(pos_begin[0]) + ' ' + str(pos_begin[1]) + ' '
                            + str(min(pos_end[0] + 2, 4070 + (img.width - 1) * 2)) + ' ' + str(pos_end[1]) + '~gge'
                            + str(cnt) + '~0\",\n')
                        cnt += 1
                    else:
                        f.write(
                            '    \"CIRCLE~' + str(pos_begin[0]) + '~' + str(pos_begin[1]) + '~' + str(d / 4) + '~'
                            + str(d / 2) + '~7~gge' + str(cnt) + '~0~~S$8' + '~circle_gge' + str(cnt + 3)
                            + ',circle_gge' + str(cnt + 6) + '\",\n')
                        cnt += 1
                    shift_flag = True
    with open('./part2.txt', 'r') as p:
        f.write(p.read())
